//
//  EpointMailMainViewController.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-1-27.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "EpointMailMainViewController.h"
#import "UIView+Addtions.h"
#import "MailMainTableViewCell.h"
#import "EpointMailSendViewController.h"
#import "EpointMailListViewController.h"

#import "Mail_GetUnReceiveCount_Task.h"
#import "User_GetInfo_Task.h"

#import "FPPopoverController.h"
#import "PGTitleView.h"
#import "PopElementView.h"
#import "EpointScrollTap.h"

#define MailGetUnReceiveCountTaskId 1
#define UserGetInfoTaskId 2

@interface EpointMailMainViewController () <UITableViewDataSource, UITableViewDelegate, FPPopoverControllerDelegate, PGTitleViewDelegate, PopElementViewDelegate,EpointScrollTapDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) EpointMailListViewController *sendListCtrl;
@property (nonatomic, strong) EpointMailListViewController *inboxListCtrl;
@property (nonatomic, strong) EpointMailListViewController *taskListCtrl;
@property (nonatomic, strong) FPPopoverController *popoverCtrl;
@property (nonatomic, strong) PGTitleView *titleView;
@property (nonatomic, strong) PopElementView *elementView;

@property (nonatomic, assign) EpointMailListViewController *selectedCtrl;

@end

@implementation EpointMailMainViewController {
    NSArray *titles;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%@", NSStringFromCGRect(self.view.bounds));
    [self switchWithIndex:0];
    [self setRightBarButton];
    [self setTitleView];
}
- (void)switchWithIndex:(int)index {

    if (_selectedCtrl) {
        [_selectedCtrl.view removeFromSuperview];
    }

    switch (index) {
        case 0:
            _selectedCtrl = self.sendListCtrl;
            break;
        case 1:
            _selectedCtrl = self.inboxListCtrl;
            break;
        case 2:
            _selectedCtrl = self.taskListCtrl;
            break;
        default:
            break;
    }

    [self.view addSubview:_selectedCtrl.view];
}

- (void)setTitleView {
    self.titleView = [[PGTitleView alloc] initWithFrame:CGRectZero];
    _titleView.text = @" 收件箱 ";
    _titleView.delegate = self;
    NSArray* titleTaps = @[@"收件箱",@"发件箱"];
    
    EpointScrollTap * scrollTap = [[EpointScrollTap alloc] initWithFrame:CGRectZero:titleTaps];
    scrollTap.delegate = self;
    if (CurrentDeviceISiPad) {
        [self.navigationItem setTitleView:scrollTap];
    }else{
        [self.navigationItem setTitleView:self.titleView];
    }
    
}

//pad title选择 索引回调
-(void)selectIndexTitle_Pad:(int)index{
    [self switchWithIndex:index];
}

- (void)setRightBarButton {
    [self setRightBarButtonItemWithImage:@"icon_nav_compose" action:@selector(newMailButtonPressed)];
}

-(void)setRightBarButtonItemWithImage:(NSString *)image action:(SEL)action
{
    if (ISIOS7) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:image] style:UIBarButtonItemStyleBordered target:self action:action];
    }
    else
    {
        UIImage *img =[UIImage imageNamed:image];
        UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
        [rightButton setImage:img forState:UIControlStateNormal];
        [rightButton addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    }
}

- (void)newMailButtonPressed {
    NSMutableDictionary *params = initParam;
    EpointMailSendViewController *mailSendCtrl = [[EpointMailSendViewController alloc] initWithParams:params];
    [self.navigationController pushViewController:mailSendCtrl animated:YES];
}

- (EpointMailListViewController *)sendListCtrl {
    if (_sendListCtrl == nil) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:self.passParam];
        // TODO: indox add some properties
        [params setObject:@"0" forKey:@"MailTpye"];
        _sendListCtrl = [[EpointMailListViewController alloc] initWithParams:params];
        _sendListCtrl.parentCtrl = self;
    }
    return _sendListCtrl;
}

- (EpointMailListViewController *)inboxListCtrl {
    if (_inboxListCtrl == nil) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:self.passParam];
        // TODO: indox add some properties
        [params setObject:@"1" forKey:@"MailTpye"];
        _inboxListCtrl = [[EpointMailListViewController alloc] initWithParams:params];
        _inboxListCtrl.parentCtrl = self;
    }
    return _inboxListCtrl;
}

- (EpointMailListViewController *)taskListCtrl {
    if (_taskListCtrl == nil) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithDictionary:self.passParam];
        // TODO: indox add some properties
        [params setObject:@"2" forKey:@"MailTpye"];
        _taskListCtrl = [[EpointMailListViewController alloc] initWithParams:params];
        _taskListCtrl.parentCtrl = self;
    }
    return _taskListCtrl;
}

- (FPPopoverController *)popoverCtrl {
    if (_popoverCtrl == nil) {
//        titles = @[@"收件箱", @"发件箱"];
        titles = @[@"收件箱", @"发件箱",@"任务邮件"];
        _elementView = [[PopElementView alloc] initWithFrame:CGRectMake(0, 0, 160, PopElementItemHeight*titles.count)];
        _elementView.delegate = self;
        _elementView.titles = titles;
        [_elementView selectItemAtIndex:0];

        _popoverCtrl = [[FPPopoverController alloc] initWithView:_elementView];
        _popoverCtrl.arrowDirection = FPPopoverArrowDirectionUp;
        _popoverCtrl.contentSize = CGSizeMake(170, PopElementItemHeight*titles.count+10+FP_POPOVER_ARROW_HEIGHT);
        _popoverCtrl.delegate = self;
    }
    return _popoverCtrl;
}

#pragma mark - FPPopoverControllerDelegate

-(void)popoverControllerDidDismissPopover:(FPPopoverController *)popoverController{
    _titleView.isSelected = NO;
}

-(void)presentedNewPopoverController:(FPPopoverController *)newPopoverController shouldDismissVisiblePopover:(FPPopoverController *)visiblePopoverController{
}

#pragma mark - PGTitleViewDelegate

- (void)titleViewDidSelected:(PGTitleView *)titleView {
    if (!self.popoverCtrl.showed) {
        [_popoverCtrl presentPopoverFromView:_titleView];
    }
}

#pragma mark - PopElementViewDelegate

- (void)popElementViewDidSelectedAtIndex:(int)index {
    NSLog(@"index:%d", index);
    [self switchWithIndex:index];
    _titleView.text = [titles objectAtIndex:index];
    [_popoverCtrl dismissPopoverAnimated:YES];
}

#pragma mark - Some thing old

-(void)viewWillAppear:(BOOL)animated {
//    [self startTask:@"Mail_GetUnReceiveCount_Task" withParams:nil withTaskId:MailGetUnReceiveCountTaskId];
//    [self startTask:@"User_GetInfo_Task" withParams:nil withTaskId:UserGetInfoTaskId];
    [super viewWillAppear:animated];
    [_selectedCtrl viewWillAppear:animated];
    NSLog(@"sadfd");
}

- (void)getMailInfo {
    
    self.dataArray = [[NSMutableArray alloc] initWithCapacity:3];
    NSDictionary *inboxDic = @{@"title": @"收件箱",
                               @"tips": @""};
    NSDictionary *outboxDic = @{@"title": @"发件箱",
                               @"tips": @""};
    NSDictionary *newDic = @{@"title": @"写邮件",
                               @"tips": @""};

    [_dataArray addObject:inboxDic];
    [_dataArray addObject:outboxDic];
    [_dataArray addObject:newDic];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CellIdentifier";
    MailMainTableViewCell *cell = (MailMainTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[MailMainTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    NSString *imageName;
    
    switch (indexPath.row) {
        case 0:
            imageName = @"filetype_eml_76h";
            break;
        case 1:
            imageName = @"filetype_txt_76h";
            break;
        case 2:
            imageName = @"filetype_pages_76h";
            break;
        default:
            break;
    }
    cell.leftImageView.image = [UIImage imageNamed:imageName];
    if (CurrentDeviceISiPad) {
        cell.leftImageView.size = CGSizeMake(30, 30);        
    } else {
        cell.leftImageView.size = CGSizeMake(30, 30);
    }
    cell.titleLabel.text = [[_dataArray objectAtIndex:indexPath.row] valueForKey:@"title"];
    cell.tipsLabel.text = [[_dataArray objectAtIndex:indexPath.row] valueForKey:@"tips"];
    return cell;
}


#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (CurrentDeviceISiPad) {
        return 60;
    } else {
        return 44;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:NO];    
    switch (indexPath.row) {
        case 0: {
            NSMutableDictionary *params = initParam;
            // TODO: indox add some properties
            [params setObject:@"0" forKey:@"MailTpye"];
            EpointMailListViewController *mailListCtrl = [[EpointMailListViewController alloc] initWithParams:params];
            [self.navigationController pushViewController:mailListCtrl animated:YES];
        }
            break;
        case 1: {
            NSMutableDictionary *params = initParam;
            // TODO: outbox add some properties
            [params setObject:@"1" forKey:@"MailTpye"];
            EpointMailListViewController *mailListCtrl = [[EpointMailListViewController alloc] initWithParams:params];
            [self.navigationController pushViewController:mailListCtrl animated:YES];
        }
            break;
        case 2: {
            NSMutableDictionary *params = initParam;
            // TODO: new add some properties
            EpointMailSendViewController *mailSendCtrl = [[EpointMailSendViewController alloc] initWithParams:params];
            [self.navigationController pushViewController:mailSendCtrl animated:YES];
        }
            break;
        default:
            break;
    }
    
}

#pragma mark - 

- (void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj {
    
    NSMutableArray *arr = (NSMutableArray*)obj;
    if (taskId == MailGetUnReceiveCountTaskId) {
        NSString *unreadNum = [arr lastObject];
        if ([unreadNum intValue] == 0) {
            unreadNum = @"";
        }
        NSDictionary *inboxDic = @{@"title": @"收件箱",
                                   @"tips": unreadNum};
        [_dataArray replaceObjectAtIndex:0 withObject:inboxDic];
        [_tableView reloadData];
    } else if (taskId == UserGetInfoTaskId) {
        
        BOOL isSuccess = [[arr objectAtIndex:0] boolValue];
        if (isSuccess) {
            NSArray *infoArray = [arr lastObject];
            NSString *NewMailsCount = [infoArray objectAtIndex:0];
            //NSString *MailReceiveCount = [infoArray objectAtIndex:2];
            NSString *MailSendCount = [infoArray objectAtIndex:3];
            
            if ([NewMailsCount intValue] == 0) {
                NewMailsCount = @"";
            }

            NSDictionary *inboxDic = @{@"title": @"收件箱",
                                       @"tips": NewMailsCount};
            [_dataArray replaceObjectAtIndex:0 withObject:inboxDic];
            
            NSDictionary *outboxDic = @{@"title": @"发件箱",
                                       @"tips": [NSString stringWithFormat:@"%@", MailSendCount]};
            [_dataArray replaceObjectAtIndex:0 withObject:inboxDic];
            [_dataArray replaceObjectAtIndex:1 withObject:outboxDic];
            [_tableView reloadData];
        }
    }
}

@end

//    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
//    if (CurrentDeviceISiPad) {
//        _tableView.width = AppWidth;
//        _tableView.height = AppHeight - SystemTakeHeight;
//    }
//    _tableView.height = AppHeight - SystemTakeHeight;
//    _tableView.delegate = self;
//    _tableView.dataSource = self;
//    _tableView.backgroundView = nil;
//    _tableView.backgroundColor = [UIColor clearColor];
//    [self.view setBackgroundColor:COLOR(239, 239, 243)];
//    [self.view addSubview:_tableView];
//
//    [self getMailInfo];